﻿#include "WorkThread.h"
#include "DBService.h"
#include "DataManger.h"

WorkThread::WorkThread(QObject *parent)
	: QThread(parent)
{
	iRefCount = 0;
	pDBService = NULL;
	pDataManger = NULL;
}

WorkThread::~WorkThread()
{
	if (pDBService != NULL)
	{
		pDBService->deleteLater();
		pDBService = NULL;
	}

	if (pDataManger == NULL)
	{
		pDataManger->deleteLater();
		pDataManger = NULL;
	}
}

int WorkThread::getRefCount() const
{
	return iRefCount;
}

QJsonObject WorkThread::requestData(const QString & method, const QByteArray & request)
{
	mutexThread.lock();
	++iRefCount;

	if (pDataManger)
	{
        const QJsonObject & object = pDataManger->requestData(method, request);
		--iRefCount;
		mutexThread.unlock();
		return object;
	}
		

	QJsonObject object;
	object.insert("Error", "Data Manger is NULL");

	--iRefCount;
	mutexThread.unlock();
	return object;
}

void WorkThread::run()
{
	pDBService = new QDBService();
	if (pDBService->init())
	{
		pDataManger = new DataManger(pDBService);
	}
}
